<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Python," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="Python 字典&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字典是另一种可变容器模型，切可存储任意类型对象。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字典是 Python 中唯一的映射类型（哈希表） &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#1">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="Python 字典（Dictionary）">
<meta property="og:url" content="https://hcldirgit.github.io/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.8 字典/10. Python 字典（Dictionary）/index.html">
<meta property="og:site_name" content="失落的乐章">
<meta property="og:description" content="Python 字典&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字典是另一种可变容器模型，切可存储任意类型对象。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字典是 Python 中唯一的映射类型（哈希表） &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#1">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-08-10T05:56:34.023Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python 字典（Dictionary）">
<meta name="twitter:description" content="Python 字典&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字典是另一种可变容器模型，切可存储任意类型对象。 &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;字典是 Python 中唯一的映射类型（哈希表） &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#1">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://hcldirgit.github.io/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.8 字典/10. Python 字典（Dictionary）/"/>





  <title>Python 字典（Dictionary） | 失落的乐章</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', '85*****1', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?87980c**************99ec5e26fb5";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>











  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">失落的乐章</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">技术面前，永远都是学生。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-message">
          <a href="/message" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-external-link"></i> <br />
            
            留言
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://hcldirgit.github.io/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.8 字典/10. Python 字典（Dictionary）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="失落的乐章">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/0.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="失落的乐章">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python 字典（Dictionary）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-10T14:00:36+08:00">
                2017-08-10
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Python-字典"><a href="#Python-字典" class="headerlink" title="Python 字典"></a>Python 字典</h1><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;字典是另一种可变容器模型，切可存储任意类型对象。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;字典是 Python 中唯一的映射类型（哈希表）</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;字段对象是可变的，但是字典的键必须使用 <code>可变对象</code> ，一个字典中可以使用不同类型的键值。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;字典的每个键值（key=&gt;value）对用冒号(:)分割，每个对之间用逗号(,)分割，整个字典包括在花括号({})中，格式如下所示：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">d = &#123;key1 ： value1,key2 : value2 &#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;键必须是唯一的，但值则不必。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;值可以去任何数据类型，但键必须是不可变的，如字符串，数字或元组。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;一个简单的字典实例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">dict = &#123;<span class="string">'Alice'</span>:<span class="string">'2341'</span>, <span class="string">'Beth'</span>: <span class="string">'9102'</span>, <span class="string">'Cecil'</span>: <span class="string">'3258'</span>&#125;</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;也可如此创建字典：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">dict1 = &#123; <span class="string">'abc'</span>: <span class="number">456</span>&#125;;</div><div class="line">dict2 = &#123; <span class="string">'abc'</span>: <span class="number">123</span>, <span class="number">98.6</span><span class="string">" 37 &#125;;</span></div></pre></td></tr></table></figure>
<h2 id="访问字典里的值"><a href="#访问字典里的值" class="headerlink" title="访问字典里的值"></a>访问字典里的值</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;把相应的键放入熟悉的方括号</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#/usr/bin/python</span></div><div class="line"></div><div class="line">dict = &#123;<span class="string">'Name'</span>: <span class="string">'Zara'</span>, <span class="string">'Age'</span>: <span class="number">7</span>, <span class="string">'Class'</span>: <span class="string">'First'</span>&#125;;</div><div class="line"></div><div class="line"><span class="keyword">print</span> <span class="string">"dict['Name']: "</span>, dict[<span class="string">'Name'</span>];</div><div class="line"><span class="keyword">print</span> <span class="string">"dict['Age']: "</span>, dict[<span class="string">'Age'</span>];</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输出结果为：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">dict[<span class="string">'Name'</span>]:  Zara</div><div class="line">dict[<span class="string">'Age'</span>]:  <span class="number">7</span></div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;如果用字典里没有的键访问数据，会输出如下错误：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"> </div><div class="line">dict = &#123;<span class="string">'Name'</span>: <span class="string">'Zara'</span>, <span class="string">'Age'</span>: <span class="number">7</span>, <span class="string">'Class'</span>: <span class="string">'First'</span>&#125;;</div><div class="line"> </div><div class="line"><span class="keyword">print</span> <span class="string">"dict['Alice']: "</span>, dict[<span class="string">'Alice'</span>];</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;实例输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">dict[<span class="string">'Alice'</span>]: </div><div class="line">Traceback (most recent call last):</div><div class="line">  File <span class="string">"test.py"</span>, line <span class="number">5</span>, <span class="keyword">in</span> &lt;module&gt;</div><div class="line">    <span class="keyword">print</span> <span class="string">"dict['Alice']: "</span>, dict[<span class="string">'Alice'</span>];</div><div class="line">KeyError: <span class="string">'Alice'</span></div></pre></td></tr></table></figure>
<h2 id="修改字典"><a href="#修改字典" class="headerlink" title="修改字典"></a>修改字典</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;向字典添加新内容的方法是增加新个键/值对，修改或删除已有键/值对：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"> </div><div class="line">dict = &#123;<span class="string">'Name'</span>: <span class="string">'Zara'</span>, <span class="string">'Age'</span>: <span class="number">7</span>, <span class="string">'Class'</span>: <span class="string">'First'</span>&#125;;</div><div class="line"> </div><div class="line">dict[<span class="string">'Age'</span>] = <span class="number">8</span>; <span class="comment"># update existing entry</span></div><div class="line">dict[<span class="string">'School'</span>] = <span class="string">"DPS School"</span>; <span class="comment"># Add new entry</span></div><div class="line"> </div><div class="line"> </div><div class="line"><span class="keyword">print</span> <span class="string">"dict['Age']: "</span>, dict[<span class="string">'Age'</span>];</div><div class="line"><span class="keyword">print</span> <span class="string">"dict['School']: "</span>, dict[<span class="string">'School'</span>];</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">dict[<span class="string">'Age'</span>]:  <span class="number">8</span></div><div class="line">dict[<span class="string">'School'</span>]:  DPS School</div></pre></td></tr></table></figure>
<h2 id="删除字典元素"><a href="#删除字典元素" class="headerlink" title="删除字典元素"></a>删除字典元素</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;能删除单一的元素也能清空字典，清空只需一向操作。<br>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;显示删除一个字典用 del 命令：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"><span class="comment"># -*- coding: UTF-8 -*-</span></div><div class="line"> </div><div class="line">dict = &#123;<span class="string">'Name'</span>: <span class="string">'Zara'</span>, <span class="string">'Age'</span>: <span class="number">7</span>, <span class="string">'Class'</span>: <span class="string">'First'</span>&#125;;</div><div class="line"> </div><div class="line"><span class="keyword">del</span> dict[<span class="string">'Name'</span>]; <span class="comment"># 删除键是'Name'的条目</span></div><div class="line">dict.clear();     <span class="comment"># 清空词典所有条目</span></div><div class="line"><span class="keyword">del</span> dict ;        <span class="comment"># 删除词典</span></div><div class="line"> </div><div class="line"><span class="keyword">print</span> <span class="string">"dict['Age']: "</span>, dict[<span class="string">'Age'</span>];</div><div class="line"><span class="keyword">print</span> <span class="string">"dict['School']: "</span>, dict[<span class="string">'School'</span>];</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;但这会引发一个异常，因为用 del 后字典不再存在：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">dict[<span class="string">'Age'</span>]:</div><div class="line">Traceback (most recent call last):</div><div class="line">  File <span class="string">"test.py"</span>, line <span class="number">8</span>, <span class="keyword">in</span> &lt;module&gt;</div><div class="line">    <span class="keyword">print</span> <span class="string">"dict['Age']: "</span>, dict[<span class="string">'Age'</span>];</div><div class="line">TypeError: <span class="string">'type'</span> object <span class="keyword">is</span> unsubscriptable</div></pre></td></tr></table></figure>
<h2 id="字典键的特性"><a href="#字典键的特性" class="headerlink" title="字典键的特性"></a>字典键的特性</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;字典值可以没有限制地取任何 Python 对象，既可以是标准的对象，也可以是用户定义的，但键不行。</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;两个重要的点需要记住</p>
<ol>
<li>不允许同一个键出现两次。创建时如果同一个键被赋值两次，后一个值会被记住：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"></div><div class="line">dict = &#123;<span class="string">'Name'</span>:<span class="string">'zata'</span>, <span class="string">'Age'</span>: <span class="number">7</span>, <span class="string">'Name'</span>: <span class="string">'Manni'</span>&#125;;</div><div class="line"></div><div class="line"><span class="keyword">print</span> <span class="string">"dict['Name']: "</span>, dict[<span class="string">'Name'</span>];</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输出结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">dict[<span class="string">'Name'</span>]: Manni</div></pre></td></tr></table></figure>
<ol>
<li>键必须不可变，所以可以用数字，字符串或元组充当，所以用列表就不行：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"> </div><div class="line">dict = &#123;[<span class="string">'Name'</span>]: <span class="string">'Zara'</span>, <span class="string">'Age'</span>: <span class="number">7</span>&#125;;</div><div class="line"> </div><div class="line"><span class="keyword">print</span> <span class="string">"dict['Name']: "</span>, dict[<span class="string">'Name'</span>];</div></pre></td></tr></table></figure>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;输出结果：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">Traceback (most recent call last):</div><div class="line">  File <span class="string">"test.py"</span>, line <span class="number">3</span>, <span class="keyword">in</span> &lt;module&gt;</div><div class="line">    dict = &#123;[<span class="string">'Name'</span>]: <span class="string">'Zara'</span>, <span class="string">'Age'</span>: <span class="number">7</span>&#125;;</div><div class="line">TypeError: list objects are unhashable</div></pre></td></tr></table></figure>
<h2 id="字典内置函数-amp-方法"><a href="#字典内置函数-amp-方法" class="headerlink" title="字典内置函数&amp;方法"></a>字典内置函数&amp;方法</h2><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Python 字典包含了以下内置函数：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>函数及描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0/1.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20cmp(" target="_blank" rel="external">cmp(dict1, dict2)</a>%E6%96%B9%E6%B3%95.md)，较两个字典元素</td>
</tr>
<tr>
<td>2</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0/2.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20len(" target="_blank" rel="external">len(dict)</a>%E6%96%B9%E6%B3%95.md)，计算字典元素个数，既键的总和。</td>
</tr>
<tr>
<td>3</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0/3.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20str(" target="_blank" rel="external">str(dict)</a>%E6%96%B9%E6%B3%95.md)，输出字典可打印的字符串表示。</td>
</tr>
<tr>
<td>4</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E5%87%BD%E6%95%B0/4.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20type(" target="_blank" rel="external">type(variable)</a>%E6%96%B9%E6%B3%95.md)，返回输入的变量类型，如果变量是字典就返回字典类型。</td>
</tr>
</tbody>
</table>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Python 字典包含了以下内置方法：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>函数及描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/1.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20clear(" target="_blank" rel="external">dict.clear()</a>%E6%96%B9%E6%B3%95.md)，删除字典内所有元素</td>
</tr>
<tr>
<td>2</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/2.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20copy(" target="_blank" rel="external">dict.copy()</a>%20%E6%96%B9%E6%B3%95.md)，返回一个字典的浅复制</td>
</tr>
<tr>
<td>3</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/3.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20fromkeys(" target="_blank" rel="external">dict.fromkeys(seq[, val]))</a>%E6%96%B9%E6%B3%95.md)，创建一个新字典，以序列 seq 中元素做字典的键，val 为字典所有键对应的初始值</td>
</tr>
<tr>
<td>4</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/4.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20get(" target="_blank" rel="external">dict.get(key, default=None)</a>%E6%96%B9%E6%B3%95.md)，返回指定键的值，如果值不在字典中返回default值</td>
</tr>
<tr>
<td>5</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/5.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20has_key(" target="_blank" rel="external">dict.has_key(key)</a>%E6%96%B9%E6%B3%95.md)，如果键在字典dict里返回true，否则返回false</td>
</tr>
<tr>
<td>6</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/6.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20items(" target="_blank" rel="external">dict.items()</a>%E6%96%B9%E6%B3%95.md)，以列表返回可遍历的(键, 值) 元组数组</td>
</tr>
<tr>
<td>7</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/7.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20keys(" target="_blank" rel="external">dict.keys()</a>%E6%96%B9%E6%B3%95.md)，以列表返回一个字典所有的键</td>
</tr>
<tr>
<td>8</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/8.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20setdefault(" target="_blank" rel="external">dict.setdefault(key, default=None)</a>%E6%96%B9%E6%B3%95.md)，和get()类似, 但如果键不存在于字典中，将会添加键并将值设为default</td>
</tr>
<tr>
<td>9</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/9.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20update(" target="_blank" rel="external">dict.update(dict2)</a>%E6%96%B9%E6%B3%95.md)，把字典dict2的键/值对更新到dict里</td>
</tr>
<tr>
<td>10</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/10.%20Python%20%E5%AD%97%E5%85%B8%EF%BC%88Dictionary%EF%BC%89%20values(" target="_blank" rel="external">dict.values()</a>%E6%96%B9%E6%B3%95.md)，以列表返回字典中的所有值</td>
</tr>
<tr>
<td>11</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/11.%20Python%20%E5%AD%97%E5%85%B8%20pop(" target="_blank" rel="external">pop(key[,default])</a>%E6%96%B9%E6%B3%95.md)，删除字典给定键 key 所对应的值，返回值为被删除的值。key值必须给出。 否则，返回default值。</td>
</tr>
<tr>
<td>12</td>
<td><a href="https://github.com/hcldirgit/studygit/blob/master/Python%E5%AD%97%E5%85%B8%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95/12.%20Python%20%E5%AD%97%E5%85%B8%20popitem(" target="_blank" rel="external">popitem()</a>%E6%96%B9%E6%B3%95.md)，随机返回并删除字典中的一对键和值。</td>
</tr>
</tbody>
</table>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.4 Python 的变量/5. Python 的变量/" rel="next" title="Python 的变量">
                <i class="fa fa-chevron-left"></i> Python 的变量
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/10/Python/1. Python 基础篇/1. Python 基础语法/1.8 字典/扩展/Python 直接赋值、浅拷贝和深度拷贝解析/" rel="prev" title="Python 直接赋值、浅拷贝和深度拷贝解析">
                Python 直接赋值、浅拷贝和深度拷贝解析 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/0.png"
               alt="失落的乐章" />
          <p class="site-author-name" itemprop="name">失落的乐章</p>
           
              <p class="site-description motion-element" itemprop="description">失落的乐章的Blog</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">627</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hcldirgit" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Python-字典"><span class="nav-number">1.</span> <span class="nav-text">Python 字典</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#访问字典里的值"><span class="nav-number">1.1.</span> <span class="nav-text">访问字典里的值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改字典"><span class="nav-number">1.2.</span> <span class="nav-text">修改字典</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除字典元素"><span class="nav-number">1.3.</span> <span class="nav-text">删除字典元素</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字典键的特性"><span class="nav-number">1.4.</span> <span class="nav-text">字典键的特性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字典内置函数-amp-方法"><span class="nav-number">1.5.</span> <span class="nav-text">字典内置函数&方法</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">失落的乐章</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
